package com.miyu.taskjob.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.miyu.taskjob.service.TaskJobService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 任务工作服务impl
 * @author longm
 * @date 2022/12/31
 */
@Slf4j
@Service
public class TaskJobServiceImpl implements TaskJobService {
    @Autowired
    private Scheduler scheduler;


    /**
     * addjob
     * @param job 工作
     * @return {@link JSONObject}
     */
    @Override
    public JSONObject addjob(JSONObject job) {
        String jName = job.getString("jName");
        String jGroup = job.getString("jGroup");
        String tName = job.getString("tName");
        String tGroup = job.getString("tGroup");
        String cron = job.getString("cron");
        try {
            // 构建JobDetail
            JobDetail jobDetail = JobBuilder.newJob(BuildTaskJob.class)
                    .withIdentity(jName, jGroup)
                    .build();
            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(tName, tGroup)
                    .startNow()
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                    .build();
            // 启动调度器
            scheduler.start();
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (Exception e) {
            log.info("创建定时任务失败" + e);
        }
        return null;
    }
}
